package controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import config.AlipayConfig;
import pojo.*;
import service.OrderService;
import service.impl.OrderServiceimpl;
import utils.UUIDUtils;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;
import java.util.Date;

/**
 * @author LiangHaiBo
 * @version 1.0
 * @date 2021.9.10 上午 11:0
 *
 * 订单模块
 */
@WebServlet("/order")
public class OrderServlet extends BaseServlet {
    /**
     * 添加订单
     */

    public String addOrder(HttpServletRequest request, HttpServletResponse response) {
        User user = (User) request.getSession().getAttribute("user");
        /*//判断用户是否登录
        if (user == null) {
            *//*request.setAttribute("msg", "你尚未登录,请前往<a href='http://localhost:8080/RaclMall_System_admin_war_exploded/user?methodName=loginUI'>登录</a>");*//*
            request.setAttribute("msg", "你尚未登录,请前往<a href='/user?methodName=loginUI'>登录</a>");
            return "jsp/msg.jsp";
        }*/
        //用户存在
        //封装订单实体
        Order order = new Order();

        order.setOid(UUIDUtils.getId());//订单的编号
        order.setOrdertime(new Date());//下单时间
       /* Date date = new Date();
        LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
        order.setOrdertime(localDateTime);*/

        //从session中先获取购物车:Cart
        Cart cart = (Cart) request.getSession().getAttribute("cart");
        order.setTotal(cart.getTotalMoney());//订单总额
        /*order.setAddress("山东省德州市");//收货地址
        order.setName(user.getName());//收货人
        order.setTelephone("1556172889");//收货人电话*/
        Collection<CartItem> items = cart.getItems();
        for (CartItem cartItem : items) {
            OrderItem orderItem = new OrderItem();
            orderItem.setItemid(UUIDUtils.getId());
            orderItem.setCount(cartItem.getCount());
            orderItem.setSubtotal(cartItem.getSubTotal());
            orderItem.setProduct(cartItem.getProduct());
            orderItem.setOrder(order);
            order.getItems().add(orderItem);
        }

        order.setUser(user);
        //调用订单的业务接口
        OrderService orderService = new OrderServiceimpl();
        orderService.addOrder(order);

        //将订单存放在request域中
        request.setAttribute("bean", order);

        request.getSession().removeAttribute("cart");

       /* return "/jsp/order_info.jsp";*/
        return "/order?methodName=getOrderlist&currentPage=1";
    }

    /**
     * 分页查询我的订单列表
     * @param request
     * @param response
     * @return
     */
    public String getOrderlist(HttpServletRequest request,HttpServletResponse response){
        User user = (User) request.getSession().getAttribute("user");
        String curPage = request.getParameter("currentPage");
        int currentPage = Integer.parseInt(curPage);//当前页
        int pageSize = 3;//每页显示3条
        //调用业务接口方法
        OrderService orderService = new OrderServiceimpl();
        PageBean<Order> pb = orderService.getOrderbyPage(currentPage,pageSize,user);

        request.setAttribute("pb",pb);
        return "/jsp/order_list.jsp";

    }

    /**
     * 查询订单
     * @param request
     * @param response
     * @return
     */
    public String getById(HttpServletRequest request,HttpServletResponse response){
        //接收订单参数
        String oid = request.getParameter("oid");
        OrderService orderService = new OrderServiceimpl();
        Order order = orderService.getById(oid);

        request.setAttribute("bean",order);

        return "/jsp/order_info.jsp";
    }

    /**
     * 支付宝支付
     * @param request
     * @param response
     * @return
     * @throws IOException
     * @throws IOException
     */
    public String pay(HttpServletRequest request,HttpServletResponse response) throws IOException, IOException {

        //接受参数
        String address=request.getParameter("address");
        String name=request.getParameter("name");
        String telephone=request.getParameter("telephone");
        String oid=request.getParameter("oid");

        //调用业务接口
        OrderService orderService = new OrderServiceimpl() ;
        //调用业务接口 通过订单变化获取订单
        Order order = orderService.getById(oid);


        //封装订单 其他数据:收货人,地址.电话,更新订单表
        order.setAddress(address);
        order.setName(name);
        order.setTelephone(telephone);
        //更新order
        //调用业务接口
        orderService.update(order);

        //向支付宝发送请求
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id,
                AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key,
                AlipayConfig.sign_type);
        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = order.getOid();  //订单编号
        //付款金额，必填
        String total_amount = order.getTotal().toString();
        //订单名称，必填
        String subject = "Rice·Mall商品支付";
        //商品描述，可空
        String body = "亲,请您留下宝贵的建议吧";
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\"," + "\"total_amount\":\""
                + total_amount + "\"," + "\"subject\":\"" + subject + "\"," + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //若想给BizContent增加其他可选请求参数，以增加自定义超时时间参数timeout_express来举例说明
        //alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
        //        + "\"total_amount\":\""+ total_amount +"\","
        //        + "\"subject\":\""+ subject +"\","
        //        + "\"body\":\""+ body +"\","
        //        + "\"timeout_express\":\"10m\","
        //        + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节
        AlipayTradePagePayResponse alipayResponse = null;
        try {
            alipayResponse=alipayClient.pageExecute(alipayRequest);
            System.out.println(alipayResponse.getBody());
            System.out.println(alipayResponse.getMsg());
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().write(alipayResponse.getBody());

        return  null ;
    }

}

